<?php

namespace app\index\controller;

use think\Db;

class Coupon extends Base
{

    public function getCouponList()
    {
        $couponType=['<>',1003];
        $res = model('coupon')->where(['couponType'=>$couponType])->where(function ($query) {
            $query->where(['status'=>1,'dateType'=>0]);
        })->whereOr(function ($query) {
            $query->where(['status'=>1,'dateType'=>1,'endTime'=>['> time',time()]]);
        })->paginate(10)->toArray();

        $res ? $this->suc($res): $this->err('获取优惠券列表失败');


    }

    /**
     * 获取下单优惠券列表
     */

    public function getOrderCouponList()
    {
        $where=[];
        input('couponType') ?  $where['couponType']=input('couponType'):$this->err('缺少优惠券类型');

        $res = model('coupon')->where($where)->where(function ($query) {
            $query->where(['status'=>1,'dateType'=>0]);
        })->whereOr(function ($query) {
            $query->where(['status'=>1,'dateType'=>1,'endTime'=>['> time',time()]]);
        })->paginate(10)->toArray();

        $res ? $this->suc($res): $this->err('获取优惠券列表失败');


    }

    /**
     * 领取优惠券
     */
    public function pickCoupon()
    {
        $where = [];
        $c_data = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键！');
        input('couponId') ? $where['couponId'] = input('couponId') : $this->err('缺少优惠券主键！');

        //验证用户
        $user=model('user')->where(['id'=>$where['cid']])->count();
        if(!$user){
            $this->err('用户编码错误！');
        }
        //验证优惠券
        $coupon=model('coupon')->where(['id'=>$where['couponId']])->count();
        if(!$coupon){
            $this->err('优惠券编码错误！');
        }

        $uc_res = model('user_coupon')->where($where)->select();
        $c_res =  model('coupon')->where(['id' => $where['couponId']])->find();
        $dateType = $c_res['dateType'];
        $pickCount = $c_res['pickCount'];
        $perLimit = $c_res['perLimit'];
        $total = $pickCount + 1;
        $count = count($uc_res);
        // 判断领取优惠券是否达到上限
        if ($count < $perLimit) {
            //判断库存优惠券是否足够
            if ($total <= $c_res['total']) {
                //判断用户领取的优惠券类型  0-优惠券类型为固定时间
                if ($dateType == 0) {
                    $dateLimit = $c_res['dateLimit'] * 86400;
                    $createTime = createTime();
                    $overTime = strtotime($createTime) + $dateLimit;
                    $data = [
                        'overTime' => date('Y-m-d H:i:s', $overTime),
                    ];
                } //判断用户领取的优惠券类型  1-优惠券类型为指定时间
                elseif ($dateType == 1) {
                    $data = [
                        'overTime' => $c_res['endTime'],
                    ];

                } else {
                    $this->err('优惠券类型错误！');
                }
                $uc_data = [
                    'cid' => $where['cid'],
                    'couponId' => $where['couponId'],
                    'createTime' => createTime(),
                    'overTime' => $data['overTime']
                ];
                $pickCount = $pickCount + 1;
                $c_data['pickCount'] = $pickCount;
                $c_data['id'] = $where['couponId'];
                // 启动事务
                Db::startTrans();
                try {
                    model('coupon')->editData($c_data, $c_data['id']);
                    $res = model('user_coupon')->editData($uc_data);
                    // 提交事务
                    Db::commit();
                    $res ? $this->suc('领取成功！') : $this->err('领取失败');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->err('操作失败！');
                }
            } else {
                $this->err('优惠券剩余不足！');
            }
        } else {
            $this->err('您对该优惠券领取数量已达上限');
        }

    }

}
